<?php
/**
 * Created by coder meng.
 * User: coder meng
 * Date: 2018/4/9 13:46
 */
namespace app\blog\controller;
use cmf\controller\AdminBaseController;
use app\blog\model\UnitModel;
use think\Db;
class UnitController extends AdminBaseController
{
    public function index()
    {
        $data=Db::name('Unit')->select();
        $this->assign("data", $data);
        return $this->fetch();
    }
    public function add()
    {
        return $this->fetch();
    }
    public function edit()
    {
        $id = $this->request->param("id");
        $data=Db::name('Unit')->where(array('id'=>$id))->find();
        $this->assign("data", $data);
        return $this->fetch();
    }
    public function addPost()
    {
        if ($this->request->isPost()) {
            if (!empty($_POST['name'])) {
                //检测名称是否已经存在
                $ischeck=Db::name('Unit')->where(array('name'=>$_POST['name']))->count();
                if($ischeck>0){
                    $this->error("该名称已存在！");
                    exit;
                }
                Db::name('Unit')->insert($_POST);
                $this->success("添加成功！", url("Unit/index"));
            }else{
                $this->error("请为此单位指定名称！");
            }

        }
    }
    public function editPost()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param("id");
            if(!empty($_POST['name'])){
                //检测类别名称是否已经存在
                $ischeck=Db::name('Unit')->where(array('name'=>$_POST['name']))->count();
                if($ischeck<=0){
                    Db::name('Unit')->where('id',$id)->update(['name'=>$_POST['name']]);
                    $this->success("编辑成功！", url("Unit/index"));
                }else{
                    $this->error("该名称已存在！");
                    exit;
                }
            }else{
                $this->error("请填写修改内容！");
            }
        }

    }
    public function delete()
    {
        $id = $this->request->param("id");
        $status = Db::name('Unit')->delete($id);
        if (!empty($status)) {
            $this->success("删除成功！", url('Unit/index'));
        } else {
            $this->error("删除失败！");
        }
    }
    public function upStatus()
    {
        $intId     = $this->request->param("id");
        $intStatus = $this->request->param("status");
        $intStatus = $intStatus ? 1 : 0;
        if (empty($intId)) {
            $this->error(lang("请选择要修改数据！"));
        }
        $GoodsClassifyModel = new UnitModel();
        $GoodsClassifyModel->isUpdate(true)->save(["status" => $intStatus], ["id" => $intId]);
        $this->success(lang("修改成功！"));
    
    }
}